import { getToken } from '@/utils/utils';
import { Button, Card, Input, message, Select, Table } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import enums from '../../../../public/enums';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import Ellipsis from '../../../components/Ellipsis';
import styles from './index.less';
import MaskText from '@/components/MaskText';
import { fingerprintFetch } from '@/utils/request'

const { Option } = Select;

@connect(() => ({}))
export default class index extends PureComponent {
  static contextTypes = {
    permissions: PropTypes.array,
  };

  state = {
    declarer: undefined,
    phone: undefined,
    activeType: undefined,
    reviewStatus: undefined,
    activeStatus: undefined,
    curPage: 1,
    pageSize: 10,
    total: 0,
    tableData: [],
    tableLoading: false,
  };

  componentDidMount() {
    this.handleTableData();
  }

  handleTableData = () => {
    const { curPage, pageSize, declarer, phone, activeType, reviewStatus, activeStatus } =
      this.state;
    this.setState({
      tableLoading: true,
    });
    let submitData = {
      curPage,
      pageSize,
      declarer,
      phone,
      activeType,
      reviewStatus,
      activeStatus,
    };
    this.props.dispatch({
      type: 'http/postObjWithRes',
      payload: {
        url: '/deviceManagement/batchactivateresultquery/page',
        ...submitData,
      },
      callback: response => {
        if (response && response.statusCode == '0' && response.data) {
          console.log('response', response.data);

          if (!response.data.list && response.data.pagination.current > 1) {
            this.setState(
              {
                curPage: 1,
                pageSize: 10,
              },
              () => {
                this.handleTableData();
              },
            );
          } else {
            this.setState({
              tableData: response.data.list,
              total: response.data.pagination.total,
            });
          }
        } else {
          if (response.statusCode !== '0') {
            message.error(response.statusMessage);
          }
        }
        this.setState({
          tableLoading: false,
        });
      },
    });
  };

  handleSearch = () => {
    this.handleTableData();
  };

  handleReset = () => {
    this.setState(
      {
        curPage: 1,
        pageSize: 10,
        declarer: undefined,
        phone: undefined,
        activeType: undefined,
        reviewStatus: undefined,
        activeStatus: undefined,
      },
      () => {
        this.handleTableData();
      },
    );
  };

  //点击导出预警车辆
  handleExport = applyId => {
    const str = `${window.g.url}/deviceManagement/batchactivateresultquery/export/${applyId}`;
    const newOptions = {};
    newOptions.headers = { OptAuthorization: getToken() };
    fingerprintFetch(str, newOptions)
      .then(response => {
        if (response.status === 200) {
          return response.blob();
        } else {
          throw response;
        }
      })
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${applyId}-${new Date().getTime()}.xls`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      })
      .catch(() => message.error('导出失败，请稍后在试!'));
  };

  render() {
    const {
      declarer,
      phone,
      activeType,
      reviewStatus,
      activeStatus,

      tableData,
      total,
      curPage,
      pageSize,
      tableLoading,
      exportLoading,
    } = this.state;

    const {
      location: { pathname },
    } = this.props;

    const columns = [
      { title: '批次号', dataIndex: 'applyId' },
      {
        title: '申报人',
        dataIndex: 'declarer',
        render: text => <MaskText text={text} type="name" />,
      },
      {
        title: '申报电话',
        dataIndex: 'phone',
        render: text => <MaskText text={text} type="phone" />,
      },
      {
        title: '激活类型',
        dataIndex: 'activeType',
        render: text => {
          let findText = enums.vehicleType.array.find(e => e.value === text);
          return findText ? findText.label : text;
        },
      },
      // {
      //   title: '审核状态',
      //   dataIndex: 'reviewStatus',
      //   render: text => {
      //     let findText = enums.reviewStatusMap.array.find(e => e.value === text);
      //     return findText ? findText.label : text;
      //   },
      // },
      {
        title: '激活状态',
        dataIndex: 'activeStatus',
        render: text => {
          let findText = enums.activeType.array.find(e => e.value === text);
          return findText ? findText.label : text;
        },
      },
      {
        title: '操作',
        dataIndex: 'opt',
        fixed: 'right',
        align: 'center',
        render: (text: any, record: any) => {
          const btns = [];

          const exportBtn = {
            title: '导出批量激活结果',
            key: 'detail',
            auth: 'bathActivateResultQuery_export',
            Popconfirm: true,
            message: '确认导出批量激活结果？',
            onConfirm: () => this.handleExport(record.applyId),
          };

          btns.push(exportBtn);
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];

    const pagination = {
      showSizeChanger: true,
      total: total,
      current: curPage,
      pageSize: pageSize,
      showTotal: () => {
        return <span>共&nbsp;{total}&nbsp;条</span>;
      },
    };

    const tableProps = {
      columns,
      pagination,
      rowKey: 'id',
      scroll: { x: 'max-content' },
      loading: tableLoading,
      dataSource: tableData,
      onChange: pagination => {
        this.setState(
          {
            curPage: pagination.current,
            pageSize: pagination.pageSize,
          },
          () => {
            this.handleTableData();
          },
        );
      },
    };

    return (
      <div>
        <div className={styles.pateoSearch}>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>申报人:</div>
            <Input
              placeholder="请输入申报人"
              value={declarer}
              onChange={e => {
                this.setState({
                  declarer: e.target.value,
                });
              }}
            />
          </div>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>申报电话:</div>
            <Input
              placeholder="请输入申报电话"
              value={phone}
              onChange={e => {
                this.setState({
                  phone: e.target.value,
                });
              }}
            />
          </div>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>激活类型:</div>
            <Select
              value={activeType}
              placeholder="请选择激活类型"
              onChange={e => {
                this.setState({
                  activeType: e,
                });
              }}
            >
              {enums.vehicleType.array.map(e => {
                return (
                  <Option key={e.value} value={e.value}>
                    {e.label}
                  </Option>
                );
              })}
            </Select>
          </div>
          {/*<div className={styles.searchInputStr}>*/}
          {/*  <div className={styles.title}>审核状态:</div>*/}
          {/*  <Select*/}
          {/*    value={reviewStatus}*/}
          {/*    placeholder="请选择审核状态"*/}
          {/*    onChange={e => {*/}
          {/*      this.setState({*/}
          {/*        reviewStatus: e,*/}
          {/*      });*/}
          {/*    }}*/}
          {/*  >*/}
          {/*    {enums.reviewStatusMap.array.map(e => {*/}
          {/*      return (*/}
          {/*        <Option key={e.value} value={e.value}>*/}
          {/*          {e.label}*/}
          {/*        </Option>*/}
          {/*      );*/}
          {/*    })}*/}
          {/*  </Select>*/}
          {/*</div>*/}
          <div className={styles.searchInputStr}>
            <div className={styles.title}>激活状态:</div>
            <Select
              value={activeStatus}
              placeholder="请选择激活状态"
              onChange={e => {
                this.setState({
                  activeStatus: e,
                });
              }}
            >
              {enums.activeType.array
                .filter((item: any) => item.value < 3)
                .map((e: any) => {
                  return (
                    <Option key={e.value} value={e.value}>
                      {e.label}
                    </Option>
                  );
                })}
            </Select>
          </div>
          <div className={styles.searchBtn}>
            <Button
              onClick={() => this.handleSearch()}
              type={'primary'}
              style={{ marginRight: '10px' }}
            >
              查询
            </Button>
            <Button onClick={() => this.handleReset()}>重置</Button>
          </div>
        </div>
        {/* <div className={styles.pateoBtns}>
          {this.context.permissions.includes(pathname + '/goodsCarMonitorReport_export') ? (
            <div className={styles.btnItem}>
              <Button type="primary" loading={exportLoading} onClick={() => this.handleExport()}>
                导出报表
              </Button>
            </div>
          ) : null}
        </div> */}
        <Card bordered={false} style={{ marginTop: 10 }}>
          <Table {...tableProps} />
        </Card>
      </div>
    );
  }
}
